package com.landiao.core.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.landiao.common.Constant;
import com.landiao.entities.Comp;
import com.landiao.entities.SendTemplate;
import com.landiao.service.CompService;
import com.landiao.service.SendTemplateService;
import com.landiao.service.SysConfigService;


/**
 * 系统初始化监听器,在系统启动时运行,进行一些初始化工作
 *
 */
public class InitListener  implements javax.servlet.ServletContextListener {
	protected final Logger log = LoggerFactory.getLogger(getClass());
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
		//需主动关闭其他线程，才能彻底关闭tomcat
        Scheduler startQuertz = (Scheduler) webApplicationContext
                .getBean("quartzSche");
        if(startQuertz != null) {
            try {
				startQuertz.shutdown();
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		log.debug("启动");
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		
		CompService compService = webApplicationContext.getBean(CompService.class);
		List<Comp> compList = compService.getAll();
		if(compList!=null&&compList.size()==1){
			Constant.comp = compList.get(0);
		}else{
			throw new RuntimeException("too more comp");
		}
		SysConfigService sysConfigService = webApplicationContext.getBean(SysConfigService.class);
		sysConfigService.initSysConfigMap();//缓存系统配置
		
		SendTemplateService tempService = webApplicationContext.getBean(SendTemplateService.class);
		List<SendTemplate> tempList = tempService.getAll();
		if(tempList!=null&&tempList.size()>0){
			for(SendTemplate temp:tempList){
				if("VIP".equals(temp.getPublicNo()))
					Constant.VIP_TEMP_MAP.put(temp.getOriginNo(), temp);
				else if("EMPLOYEE".equals(temp.getPublicNo()))
					Constant.EMPLOYEE_TEMP_MAP.put(temp.getOriginNo(), temp);
			}
		}
	}
}
